package com.wolfking.jeesite.sso;

import com.wolfking.jeesite.entity.User;
import com.wolfking.jeesite.service.UserService;
import com.wolfking.jeesite.service.SysKvCacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * sys_token缓存的服务
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月23日 下午4:20:51
 * @copyright wolfking
 */
@Slf4j
@Service
public class SysDbSsoCacheService implements SsoCacheService {

    @Autowired
    private UserService userService;

    @Autowired
    private SysKvCacheService sysKvCacheService;

    /**
     * 保存tokenID和userId到缓存
     *
     * @param user
     */
    public void saveToken(User user) {
        String s = sysKvCacheService.get(getUserCacheKey(user.getId()));
        if (Objects.nonNull(s)) {
            log.info("clear exists login info {}", s);
            try {
                clearToken(s);
            } catch (Exception e) {
                log.warn("clear exists login info error", e);
            }
        }
        Date expired = new Date(System.currentTimeMillis() + 86400000L * 90);
        sysKvCacheService.put(getTokenCacheKey(user.getTokenId()), user.getId().toString(), expired);
        sysKvCacheService.put(getUserCacheKey(user.getId()), user.getTokenId(), expired);
    }

    /**
     * 从缓存获取登录的数据
     *
     * @param tokenId
     */
    public User getTokenUser(String tokenId) {
        String s = sysKvCacheService.get(getTokenCacheKey(tokenId));
        if (StringUtils.isBlank(s)) {
            return null;
        }
        User user = userService.getById(Integer.parseInt(s));
        if (Objects.nonNull(user)) {
            user.setTokenId(tokenId);
        }
        return user;
    }

    public String clearToken(String tokenId) {
        String userId = sysKvCacheService.get(getTokenCacheKey(tokenId));
        sysKvCacheService.delete(getTokenCacheKey(tokenId));
        if (StringUtils.isNoneBlank(userId)) {
            sysKvCacheService.delete(getUserCacheKey(userId));
            return userId;
        }
        return null;
    }

    private String getUserCacheKey(Object id) {
        String userCache = "operate-user:%s";
        return String.format(userCache, id);
    }

    private String getTokenCacheKey(Object id) {
        String tokenCache = "operate-token:%s";
        return String.format(tokenCache, id);
    }
}
